import numpy as np
import math
import cv2 as cv
import time 
from filters.f import filterImg
# import librosa

# 凸透镜
def convexity(img):   
  row = img.shape[0]
  col = img.shape[1]
  channel = img.shape[2]
  newImg = np.zeros([row,col,channel],dtype=np.uint8)
  centerX = row/2
  centerY = col/2
  # radius = math.sqrt(centerX*centerX+centerY*centerY)/2
  radius = min(centerX, centerY)
  for i in range(row):
    for j in range(col):
      distance = ((i-centerX)*(i-centerX)+(j-centerY)*(j-centerY))
      newDist = math.sqrt(distance)
      newImg[i, j, :] = img[i, j, :]
      if distance<=radius**2:
        nexI = np.int(np.floor(newDist*(i-centerX)/radius+centerX))
        nexJ = np.int(np.floor(newDist*(j-centerY)/radius+centerY))
        newImg[i,j,:] = img[nexI,nexJ,:]
  return newImg

# 显示图片
def cvShow(img, duration=0):
  timestamp = str(int(time.time()))
  resHeight, resWidth = img.shape[:2]
  scale = 1
  if resWidth >= 3000:
    scale = 4
  elif resWidth >= 2000 and resWidth < 3000:
    scale = 3
  else:
    scale = 2
  img = cv.resize(img, (int(resWidth / scale), int(resHeight / scale)), interpolation=cv.INTER_AREA)
  cv.imshow(timestamp, img)
  cv.waitKey(duration)
  cv.destroyAllWindows()

# 合成以当前图片为背景的图片
def generateImg(img, target=(610, 1080), outputPath='./demo.jpg', filters=''):
  img = img if bool(filters) == False else filterImg(name=filters, img=img)
  origin = img
  (tw, th) = target
  canvas = np.ones((th, tw, 3), dtype=np.uint8) * 255
  (h, w) = img.shape[:2]
  scale = h / th
  bg = cv.resize(img, (int(w/scale), th))
  (h, w) = bg.shape[:2]
  if w < tw:
    scale = w / tw
    bg = cv.resize(img, (tw, int(h/scale)))
    (h, w) = bg.shape[:2]
    canvas[:, :] = bg[int((h-th)/2):int((h-th)/2+th), :]
  else:
    canvas[:, :] = bg[:, int((w-tw)/2):int((w-tw)/2+tw)]
  bg = cv.GaussianBlur(canvas, ksize=(83, 83), sigmaX=100, sigmaY=100)
  mask = np.ones((th, tw, 3), dtype=np.uint8) * 10
  bg = cv.addWeighted(bg, 0.8, mask, 0.2, 0)
  
  (oh, ow) = origin.shape[:2]
  scale = ow / tw
  curH = int(oh/scale)
  origin = cv.resize(origin, (tw, curH))
  if oh / ow >= 1:
    if curH >= th*0.8:
      # 纵向高度超出
      target = origin[int((curH-th*0.8)/2):int((curH-th*0.8)/2+th*0.8), :]
      h = int(th*0.9) - int(th*0.1)
      target = cv.resize(target, (tw, h))
      bg[int(th*0.1):int(th*0.9), :] = target
    else:
      # 纵向高度未超出 
      h = int((th-curH)/2+curH) - int((th-curH)/2)
      origin = cv.resize(origin, (tw, h))
      bg[int((th-curH)/2):int((th-curH)/2+curH), :] = origin
  else:
    # 横向图片
    h = int((th-oh/scale)/2+oh/scale) - int((th-oh/scale)/2)
    origin = cv.resize(origin, (tw, h))
    bg[int((th-oh/scale)/2):int((th-oh/scale)/2+oh/scale), :] = origin
  cv.imwrite(outputPath, bg)  

# 不裁切旋转图片
def rotateImgNocrop(img, angle):
  h, w = img.shape[:2]
  cX, cY = (w//2, h//2)

  M = cv.getRotationMatrix2D((cX, cY), angle=-angle, scale=1.0)
  cos = np.abs(M[0, 0])
  sin = np.abs(M[0, 1])
  nW = int((h*sin) + (w*cos))
  nH = int((h*cos) + (w*sin))

  M[0, 2] += (nW / 2) -cX
  M[1, 2] += (nH / 2) - cY
  return cv.warpAffine(img, M, (nW, nH))

# 固定宽高裁切旋转图片
def rotateImgCrop(img, angle=1):
  h, w = img.shape[:2]
  bg = np.zeros((h, w, 3), np.uint8)
  crop = rotateImgNocrop(img, angle=angle)
  cH, cW = crop.shape[:2]
  if angle == 0:
    scale = 1
  else:
    scale = 1.01 + 2*angle / 100
  crop = cv.resize(crop, (int(cW*scale), int(cH*scale)))
  cH, cW = crop.shape[:2]
  ttH = int((cH-h)/2)
  tbH = int((cH-h)/2+h)
  tlW = int((cW-w)/2) 
  trW = int((cW-w)/2+w)
  img = crop[ttH:tbH, tlW:trW]
  return img

# 获取音乐节拍
def getBeats(musicUrl):
  y, sr = librosa.load(musicUrl, sr=None)
  #tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
  onset_env = librosa.onset.onset_strength(y, sr=sr, aggregate=np.median)
  tempo, beats = librosa.beat.beat_track(onset_envelope=onset_env, sr=sr)
  beatsRes = np.array(librosa.frames_to_time(beats[:-1], sr=sr)) * 1000
  beatsRes[0] = 0
  return beatsRes